import React, { useState } from 'react';
import {
  Card,
  Form,
  Input,
  Button,
  Typography,
  Space,
  message,
  Spin,
  Tag,
  Divider,
  Tooltip,
  Row,
  Col,
} from 'antd';
import {
  PlayCircleOutlined,
  CopyOutlined,
  CheckCircleOutlined,
  ExclamationCircleOutlined,
  CloseCircleOutlined,
  DownloadOutlined,
} from '@ant-design/icons';
import axios from 'axios';

const { Title, Text, Paragraph } = Typography;
const { TextArea } = Input;

interface Candidate {
  xpath: string;
  css: string | null;
  strategy: string;
  matches: number;
  verification_status: string;
}

interface AnalyzeResponse {
  original_node_html: string;
  original_node_attributes: Record<string, string>;
  candidates: Candidate[];
}

interface FormValues {
  url: string;
  xpath: string;
  css?: string;
}

const XPathLocator: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [result, setResult] = useState<AnalyzeResponse | null>(null);

  const handleAnalyze = async (values: FormValues) => {
    setLoading(true);
    try {
      const response = await axios.post<AnalyzeResponse>(
        'http://127.0.0.1:8000/api/locate/analyze',
        {
          url: values.url,
          xpath: values.xpath,
          css: values.css || null,
        }
      );
      setResult(response.data);
      message.success('分析完成！');
    } catch (error: any) {
      console.error('分析失败:', error);
      const errorMsg = error.response?.data?.detail || '分析失败，请检查输入参数';
      message.error(errorMsg);
    } finally {
      setLoading(false);
    }
  };

  const copyToClipboard = async (text: string) => {
    try {
      await navigator.clipboard.writeText(text);
      message.success('已复制到剪贴板');
    } catch (error) {
      message.error('复制失败');
    }
  };

  const exportResults = () => {
    if (!result) return;
    
    const exportData = {
      timestamp: new Date().toISOString(),
      original_node: {
        html: result.original_node_html,
        attributes: result.original_node_attributes,
      },
      candidates: result.candidates,
    };
    
    const blob = new Blob([JSON.stringify(exportData, null, 2)], {
      type: 'application/json',
    });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `xpath-analysis-${Date.now()}.json`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
    message.success('导出成功');
  };

  const getStatusIcon = (status: string) => {
    switch (status) {
      case 'pass':
        return <CheckCircleOutlined style={{ color: '#52c41a' }} />;
      case 'warn':
        return <ExclamationCircleOutlined style={{ color: '#faad14' }} />;
      case 'fail':
        return <CloseCircleOutlined style={{ color: '#ff4d4f' }} />;
      default:
        return null;
    }
  };

  const getStatusText = (status: string) => {
    switch (status) {
      case 'pass':
        return '通过';
      case 'warn':
        return '警告';
      case 'fail':
        return '失败';
      default:
        return '未知';
    }
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'pass':
        return 'success';
      case 'warn':
        return 'warning';
      case 'fail':
        return 'error';
      default:
        return 'default';
    }
  };

  return (
    <div className="xpath-locator">
      <Title level={2} style={{ textAlign: 'center', marginBottom: 32 }}>
        XPath 泛化定位工具
      </Title>

      <Card title="输入参数" size="small">
        <Form
          form={form}
          layout="vertical"
          onFinish={handleAnalyze}
          disabled={loading}
        >
          <Form.Item
            label="目标页面URL"
            name="url"
            rules={[
              { required: true, message: '请输入目标页面URL' },
              { type: 'url', message: '请输入有效的URL' },
            ]}
          >
            <Input
              placeholder="https://example.com/page"
              size="large"
            />
          </Form.Item>

          <Form.Item
            label="原始XPath"
            name="xpath"
            rules={[{ required: true, message: '请输入原始XPath' }]}
          >
            <TextArea
              placeholder="//*[@id='content']/div[1]/h1"
              rows={3}
              size="large"
            />
          </Form.Item>

          <Form.Item
            label="CSS选择器（可选）"
            name="css"
          >
            <Input
              placeholder="#content > div:first-child > h1"
              size="large"
            />
          </Form.Item>

          <Form.Item>
            <Space>
              <Button
                type="primary"
                htmlType="submit"
                icon={<PlayCircleOutlined />}
                loading={loading}
                size="large"
              >
                开始分析
              </Button>
              {result && (
                <Button
                  icon={<DownloadOutlined />}
                  onClick={exportResults}
                  size="large"
                >
                  导出结果
                </Button>
              )}
            </Space>
          </Form.Item>
        </Form>
      </Card>

      {loading && (
        <Card>
          <div className="loading-container">
            <Spin size="large" />
            <Text style={{ marginLeft: 16 }}>正在分析页面和生成候选...</Text>
          </div>
        </Card>
      )}

      {result && (
        <>
          <Card title="原始节点信息" size="small">
            <Row gutter={16}>
              <Col span={12}>
                <Title level={5}>HTML片段</Title>
                <div className="original-node">
                  <pre>{result.original_node_html}</pre>
                </div>
              </Col>
              <Col span={12}>
                <Title level={5}>节点属性</Title>
                <div className="original-node">
                  {Object.entries(result.original_node_attributes).map(([key, value]) => (
                    <div key={key} style={{ marginBottom: 8 }}>
                      <Text strong>{key}:</Text> <Text code>{value}</Text>
                    </div>
                  ))}
                  {Object.keys(result.original_node_attributes).length === 0 && (
                    <Text type="secondary">无属性</Text>
                  )}
                </div>
              </Col>
            </Row>
          </Card>

          <Card 
            title={`泛化候选 (${result.candidates.length}个)`}
            size="small"
          >
            {result.candidates.map((candidate, index) => (
              <div
                key={index}
                className={`candidate-item status-${candidate.verification_status}`}
              >
                <div className="candidate-header">
                  <div className="candidate-strategy">
                    策略: {candidate.strategy}
                  </div>
                  <div className="candidate-status">
                    <Tag color={getStatusColor(candidate.verification_status)}>
                      {getStatusIcon(candidate.verification_status)}
                      <span style={{ marginLeft: 4 }}>
                        {getStatusText(candidate.verification_status)}
                      </span>
                    </Tag>
                    <Text type="secondary">匹配数: {candidate.matches}</Text>
                  </div>
                </div>

                <div>
                  <Text strong>XPath:</Text>
                  <div className="code-block">
                    {candidate.xpath}
                    <Tooltip title="复制XPath">
                      <Button
                        type="text"
                        size="small"
                        icon={<CopyOutlined />}
                        onClick={() => copyToClipboard(candidate.xpath)}
                        style={{ float: 'right' }}
                      />
                    </Tooltip>
                  </div>
                </div>

                {candidate.css && (
                  <div>
                    <Text strong>CSS选择器:</Text>
                    <div className="code-block">
                      {candidate.css}
                      <Tooltip title="复制CSS选择器">
                        <Button
                          type="text"
                          size="small"
                          icon={<CopyOutlined />}
                          onClick={() => copyToClipboard(candidate.css!)}
                          style={{ float: 'right' }}
                        />
                      </Tooltip>
                    </div>
                  </div>
                )}

                {candidate.verification_status === 'warn' && (
                  <div style={{ marginTop: 8 }}>
                    <Text type="warning">
                      ⚠️ 警告: 该选择器匹配了 {candidate.matches} 个元素，可能不够精确
                    </Text>
                  </div>
                )}

                {candidate.verification_status === 'fail' && (
                  <div style={{ marginTop: 8 }}>
                    <Text type="danger">
                      ❌ 失败: 该选择器未匹配到任何元素
                    </Text>
                  </div>
                )}
              </div>
            ))}

            {result.candidates.length === 0 && (
              <div style={{ textAlign: 'center', padding: 40 }}>
                <Text type="secondary">未生成任何候选，请检查输入的XPath是否有效</Text>
              </div>
            )}
          </Card>
        </>
      )}
    </div>
  );
};

export default XPathLocator;